import pygame
import pygame.locals
import sys,time,random

#   2021-05-20  09:58   by  炸天帮成员
#   即在_4_pygame_demo_Part3_OK.py的基础上，增加了对Enemy对象的区分，以求它们不会重叠到一起；
#   但是，貌似稍微有点复杂，主要是靠，self.rect.center的坐标配合Enemy图片的长与宽 来进行 两个Enemy的 隔离；
#   但最好还是另外弄一个类，继承原始的Enemy，或者重开一个类。

pygame.init()
pygame.font.init()
#Setting up FPS 
FPS = 60
FramePerSec = pygame.time.Clock()
 
#Creating colors
BLUE  = (0, 0, 255)
RED   = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
 
#Other Variables for use in the program
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
SPEED = 5
SCORE = 0
 
#Setting up Fonts
font = pygame.font.SysFont("Verdana", 60)
font_small = pygame.font.SysFont("Verdana", 20)
game_over = font.render("Game Over", True, BLACK)
 
background = pygame.image.load(".\Materials\Materials\AnimatedStreet.png")  # 注意背景图片的大小一定要和窗口设置的大小一致（或pygame.Sprite对象的有效活动范围一致）。否则，显示会出问题。
 
#Create a white screen 
DISPLAYSURF = pygame.display.set_mode((400,600))
DISPLAYSURF.fill(WHITE)
pygame.display.set_caption("Game")

Enemy_info = None 
class Enemy(pygame.sprite.Sprite):
      def __init__(self,Enemy_ID):
        super().__init__() 
        self.image = pygame.image.load(".\Materials\Materials\Enemy.png")
        self.surf = pygame.Surface((48, 93))
        if Enemy_ID == 1:
            global Enemy_info
            position_Y = random.randint(-20,0)
            self.rect = self.surf.get_rect(center = (random.randint(40,SCREEN_WIDTH-40), position_Y))
            Enemy_info = self.rect.center
            print('Enemy_info = ',Enemy_info)
        elif Enemy_ID == 2:
            position_X = Enemy_info[0] + 48
            position_Y = Enemy_info[1] - 93
            print('position_X = ',position_X)
            print('position_Y = ',position_Y)
            self.rect = self.surf.get_rect(center = (position_X, position_Y))
 
      def move(self,Enemy_ID):
        global Enemy_info
        global SCORE    #   在函数中引用全局变量 SCORE，即结束后，改变的值将是全局域中的SCORE变量的值
        self.rect.move_ip(0,SPEED)
        if Enemy_ID == 1:
            if (self.rect.top > 600):   
                SCORE += 1  #   即如果没有碰撞到，程序中的Enemy正常在运行，则SCORE会+1
                self.rect.center = (random.randint(40, SCREEN_WIDTH - 40), random.randint(-100,0))  # 因为需要在屏幕显示时从0开始，故Y轴需要使用负数。
                Enemy_info = self.rect.center
                print('Enemy_info = ',Enemy_info)
        elif Enemy_ID == 2:
            if (self.rect.top > 600):
                SCORE += 1  #   即如果没有碰撞到，程序中的Enemy正常在运行，则SCORE会+1，因为每辆车就是1分，所以每辆车都要+1分。
                position_X = Enemy_info[0] + random.randint(48,SCREEN_WIDTH - 40*2)
                position_Y = Enemy_info[1]  #改变这里的数值，只要不是太大，就不会出现两个Enemy叠在一起的问题
                print('position = ',(position_X,position_Y))
                self.rect = self.surf.get_rect(center = (position_X, position_Y))

 
 
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__() 
        self.image = pygame.image.load(".\Materials\Materials\Player.png")
        self.surf = pygame.Surface((44, 96))
        self.rect = self.surf.get_rect(center = (160, 520))
        
    def move(self,Player_ID):
        pressed_keys = pygame.key.get_pressed()
       #if pressed_keys[K_UP]:
            #self.rect.move_ip(0, -5)
       #if pressed_keys[K_DOWN]:
            #self.rect.move_ip(0,5)
         
        if self.rect.left > 0:
              if pressed_keys[pygame.locals.K_LEFT]:
                  self.rect.move_ip(-5, 0)
        if self.rect.right < SCREEN_WIDTH:        
              if pressed_keys[pygame.locals.K_RIGHT]:
                  self.rect.move_ip(5, 0)
                   
#Setting up Sprites        
P1 = Player()
E1 = Enemy(1)
E2 = Enemy(2)
 
#Creating Sprites Groups
enemies = pygame.sprite.Group()
enemies.add(E1)
enemies.add(E2)

all_sprites = pygame.sprite.Group()
all_sprites.add(P1)
all_sprites.add(E1)
all_sprites.add(E2)
 
#Adding a new User event 
INC_SPEED = pygame.USEREVENT + 1
pygame.time.set_timer(INC_SPEED, 1000)
 
#Game Loop
while True:
       
    #Cycles through all events occurring  
    for event in pygame.event.get():
        if event.type == INC_SPEED:
              SPEED += 0.5     
        if event.type == pygame.locals.QUIT:
            pygame.quit()
            sys.exit()
 
    DISPLAYSURF.blit(background, (0,0)) #   装载    background  至  坐标(0,0)，注意这个背景图片也要在大while循环中，且位置最好在最前面。
    scores = font_small.render(str(SCORE), True, BLACK)
    #print('scores的类型为： ',type(scores)) #   注意 scores 也为 pygame.Surface对象。
    DISPLAYSURF.blit(scores, (10,10))   #   装载    scores  至坐标(10,10)。
 
    #Moves and Re-draws all Sprites
    for entity in all_sprites:
        DISPLAYSURF.blit(entity.image, entity.rect) # 装载 image    至 pygame.rect对象上(该对象内部也有坐标数据)
        #entity.move()
    
    P1.move(None)
    E1.move(1)
    E2.move(2)
 
    #   为了便于观察    几个Enemy对象是否会发生重叠     故将此处    碰撞事件的处理函数  给注释掉了。
    #To be run if collision occurs between Player and Enemy
    # if pygame.sprite.spritecollideany(P1, enemies):
    #       pygame.mixer.Sound('.\Materials\Materials\crash.wav').play()
    #       time.sleep(0.5)
                    
    #       DISPLAYSURF.fill(RED)
    #       DISPLAYSURF.blit(game_over, (30,250)) #   装载    game_over  至坐标(30,250)。
           
    #       pygame.display.update()
    #       for entity in all_sprites:
    #             entity.kill() 
    #       time.sleep(2)
    #       pygame.quit()
    #       sys.exit()        
         
    pygame.display.update()
    FramePerSec.tick(FPS)
